//
//  BCShareRewardController.m
//  GSBlockChain
//
//  Created by guoshikeji_a on 2018/12/21.
//  Copyright © 2018 guoshikeji. All rights reserved.
//

#import "BCShareRewardController.h"

//生成二维码
#import "SGQRCode.h"
//
#import "BCUserShareRequest.h"//reqeust

@interface BCShareRewardController ()

@property (nonatomic, strong) UIScrollView *contentScroll;

@property (nonatomic, strong) UIView *snapshotContentView;

@property (nonatomic, strong) CAShapeLayer *topLayer;
//
@property (nonatomic, strong) QMUILabel *titleLabel;
/**
 *amountLabel
 */
@property (nonatomic, strong) QMUILabel *amountLabel;

/**
 *headImageView
 */
@property (nonatomic, strong) UIImageView *headImageView;
/**
 *nameLabel
 */
@property (nonatomic, strong) QMUILabel *nameLabel;

/**
 *recommend
 */
@property (nonatomic, strong) QMUILabel *recommendLabel;

/**
 *qrIV
 */
@property (nonatomic, strong) UIImageView *qrIV;

/**
 *joinCaptionLabel
 */
@property (nonatomic, strong) QMUILabel *joinCaptionLabel;

/**
 *captionLabel
 */
@property (nonatomic, strong) QMUILabel *captionLabel;


/**
 *shareRewardButton
 */
@property (nonatomic, strong) QMUIButton *shareRewardButton;


/**
 *设置后动态计算算出的contentHeight
 */
@property (nonatomic, assign) CGFloat contentHeight;

#pragma mark - data

/**
 *BCUserShareData
 */
@property (nonatomic, strong) BCUserShareData *shareData;

@end

@implementation BCShareRewardController

+ (void)showFromController:(UIViewController *)fromController {
    BControllerWindow *window = [[BControllerWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    window.windowLevel = UIWindowLevelAlert;
    BCShareRewardController *vc = [BCShareRewardController new];
    vc.showWindow = window;
    vc.fromController = fromController;
    window.rootViewController = vc;
    [window makeKeyAndVisible];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    //
    [self setupSubviews];
    //
    [self requestShareData];
}

- (void)setupSubviews {
    [self.view addSubview:self.backgroundView];
    self.backgroundView.alpha = 0.5;
    [self.backgroundView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(self.view);
    }];
    [self.view layoutIfNeeded];
    //
    [UIView animateWithDuration:0.1 animations:^{
        self.backgroundView.alpha = 0.7;
    }];
}
- (CGFloat)contentWidth {
    return self.view.frame.size.width*0.9;
}

/**
 分享数据请求完成后加载contentView
 */
- (void)loadContentView:(CGFloat)width {
    [self.view addSubview:self.contentView];
    self.contentView.layer.cornerRadius = 8.0;
    self.contentView.layer.masksToBounds = true;
    //
    self.contentView.frame = CGRectMake(0, 0, width, 600);
    
    //
    self.contentScroll = [UIScrollView new];
    self.contentScroll.showsVerticalScrollIndicator = false;
    self.contentScroll.showsHorizontalScrollIndicator = false;
    [self.contentView addSubview:self.contentScroll];
    [self.contentScroll mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(self.contentView);
    }];
    //
    UIView *scrollTopView = [UIView new];
    scrollTopView.backgroundColor = [UIColor darkMainColor];
    [self.contentScroll addSubview:scrollTopView];
    [scrollTopView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(self.contentScroll);
        make.left.mas_equalTo(self.contentScroll);
        make.width.mas_equalTo(self.contentScroll);
        make.height.mas_equalTo(1000.0);
    }];
    //
    self.snapshotContentView = [UIView new];
    [self.contentScroll addSubview:self.snapshotContentView];
    [self.snapshotContentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.contentScroll);
        make.left.mas_equalTo(self.contentScroll);
        make.width.mas_equalTo(self.contentScroll);
    }];
    
    [self.view layoutIfNeeded];
    [self setContents:width];
    [self.view layoutIfNeeded];
}
- (void)setContents:(CGFloat)width {
    if (!self.topLayer) {
        self.topLayer = [CAShapeLayer new];
        self.topLayer.fillColor = [UIColor darkMainColor].CGColor;
        [self.snapshotContentView.layer addSublayer:self.topLayer];
    }
    //视图所有padding总和
    CGFloat totalPadding = 0;
    CGFloat hScale = MIN(HeightScale, 1);
    CGFloat wScale = MIN(WidthScale, 1);
    //
    CGFloat topPadding = 26.0*hScale;//padding
    totalPadding += topPadding;
    //titleLabel
    if (!_titleLabel) {
        self.titleLabel = [QMUILabel new];
        self.titleLabel.font = [UIFont systemFontOfSize:30 weight:UIFontWeightRegular];
        self.titleLabel.textColor = [UIColor qmui_colorWithHexString:@"#FFFFFF"];
        self.titleLabel.numberOfLines = 0;
        self.titleLabel.textAlignment = NSTextAlignmentCenter;
        [self.snapshotContentView addSubview:self.titleLabel];
        [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(topPadding);
            make.centerX.mas_equalTo(self.snapshotContentView);
            make.width.mas_equalTo(self.snapshotContentView).offset(-30.0*wScale);
        }];
    }
    NSString *title = self.shareData.text.title;
    NSString *subTitle =self.shareData.text.harvest;
    NSString *titleString = [NSString stringWithFormat:@"%@\n%@",title,subTitle];
    NSMutableAttributedString *titleAttributedText = [[NSMutableAttributedString alloc] initWithString:titleString];
    NSRange subRange = [titleString rangeOfString:subTitle];
    if (subRange.location!=NSNotFound) {
        [titleAttributedText addAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15 weight:UIFontWeightRegular]} range:subRange];
    }
    [self.titleLabel setAttributedText:titleAttributedText];
    CGFloat titlePadding = 18.0*hScale;//padding
    totalPadding += titlePadding;
    //amountLabel
    if (!_amountLabel) {
        self.amountLabel = [QMUILabel new];
        self.amountLabel.textAlignment = NSTextAlignmentCenter;
        self.amountLabel.font = [UIFont systemFontOfSize:45 weight:UIFontWeightRegular];
        self.amountLabel.adjustsFontSizeToFitWidth = true;
        self.amountLabel.textColor = self.titleLabel.textColor;
        [self.snapshotContentView addSubview:self.amountLabel];
        [self.amountLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(self.titleLabel.mas_bottom).offset(titlePadding);
            make.centerX.mas_equalTo(self.snapshotContentView);
            make.width.mas_equalTo(self.snapshotContentView).offset(-20.0*wScale);
            make.height.mas_equalTo(60.0*HeightScale);
        }];
    }
    NSString *amount = self.shareData.grand_money;
    [self.amountLabel setText:amount];
    CGFloat amountPadding = 20.0*hScale;
    totalPadding += amountPadding;
    //headImageView
    if (!_headImageView) {
        CGFloat headImageViewHeight = 70.0*wScale;
        self.headImageView = [UIImageView new];
        self.headImageView.contentMode = UIViewContentModeScaleAspectFill;
        [self.snapshotContentView addSubview:self.headImageView];
        [self.headImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(self.amountLabel.mas_bottom).offset(amountPadding);
            make.centerX.mas_equalTo(self.snapshotContentView);
            make.width.height.mas_equalTo(headImageViewHeight);
        }];
        //
        self.headImageView.layer.masksToBounds = true;
        self.headImageView.layer.borderColor = [UIColor whiteColor].CGColor;
        self.headImageView.layer.borderWidth = 4*wScale;
        self.headImageView.layer.cornerRadius = headImageViewHeight/2;
    }
    [self.headImageView sd_setImageWithURL:[NSURL URLWithString:self.shareData.head_img] placeholderImage:LOAD_IMAGE(@"default_head")];
    CGFloat headPadding = 18.0*hScale;//padding
    totalPadding += headPadding;
    //name
    if (!_nameLabel) {
        self.nameLabel = [QMUILabel new];
        self.nameLabel.font = [UIFont systemFontOfSize:18 weight:UIFontWeightRegular];
        self.nameLabel.textColor = [UIColor qmui_colorWithHexString:@"#222222"];
        self.nameLabel.lineBreakMode = NSLineBreakByTruncatingMiddle;
        self.nameLabel.textAlignment = NSTextAlignmentCenter;
        self.nameLabel.numberOfLines = 0;
        [self.snapshotContentView addSubview:self.nameLabel];
        [self.nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(self.headImageView.mas_bottom).offset(headPadding);
            make.centerX.mas_equalTo(self.snapshotContentView);
            make.width.mas_equalTo(self.snapshotContentView).offset(-30.0*wScale);
        }];
    }
    self.nameLabel.text = self.shareData.nickname;
    CGFloat namePadding = 3.0*hScale;//padding
    totalPadding += namePadding;
    //recommend
    if (!_recommendLabel) {
        self.recommendLabel = [QMUILabel new];
        self.recommendLabel.textColor = [UIColor qmui_colorWithHexString:@"#666666"];
        self.recommendLabel.textAlignment = NSTextAlignmentCenter;
        self.recommendLabel.numberOfLines = 0;
        self.recommendLabel.font = [UIFont systemFontOfSize:12 weight:UIFontWeightRegular];
        [self.snapshotContentView addSubview:self.recommendLabel];
        [self.recommendLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(self.nameLabel.mas_bottom).offset(namePadding);
            make.centerX.mas_equalTo(self.snapshotContentView);
            make.width.mas_equalTo(self.nameLabel);
        }];
    }
    self.recommendLabel.text = [NSString stringWithFormat:@"%@：%@",self.shareData.text.share_code,self.shareData.share_code];
    CGFloat recommendPadding = 18.0*hScale;//padding
    totalPadding += recommendPadding;
    //qrIV
    CGFloat qrHeight = 99.0*wScale;
    if (!_qrIV) {
        _qrIV = [UIImageView new];
        [self.snapshotContentView addSubview:self.qrIV];
        [self.qrIV mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(self.recommendLabel.mas_bottom).offset(recommendPadding);
            make.centerX.mas_equalTo(self.snapshotContentView);
            make.width.height.mas_equalTo(qrHeight);
        }];
    }
    NSString *qrString = self.shareData.reg_url;
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        UIImage *qrImage = [SGQRCodeGenerateManager SG_generateWithDefaultQRCodeData:qrString imageViewWidth:qrHeight];
        dispatch_async(dispatch_get_main_queue(), ^{
            self.qrIV.image = qrImage;
        });
    });
    CGFloat qrIVPadding = 10.0*hScale;//padding
    totalPadding += qrIVPadding;
    //joinCaption
    if (!_joinCaptionLabel) {
        CGFloat insetsPadding = 16.0*wScale;
        self.joinCaptionLabel = [QMUILabel new];
        self.joinCaptionLabel.textColor = [UIColor qmui_colorWithHexString:@"#ABABAB"];
        self.joinCaptionLabel.font = [UIFont systemFontOfSize:12 weight:UIFontWeightRegular];
        self.joinCaptionLabel.adjustsFontSizeToFitWidth = true;
        self.joinCaptionLabel.numberOfLines = 0;
        self.joinCaptionLabel.textAlignment = NSTextAlignmentCenter;
        self.joinCaptionLabel.contentEdgeInsets = UIEdgeInsetsMake(0, insetsPadding, 0, insetsPadding);
        [self.snapshotContentView addSubview:self.joinCaptionLabel];
        [self.joinCaptionLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(self.qrIV.mas_bottom).offset(qrIVPadding);
            make.centerX.mas_equalTo(self.qrIV);
            make.width.mas_equalTo(self.qrIV);
        }];
    }
    self.joinCaptionLabel.text = self.shareData.text.participate;
    CGFloat joinCaptionPadding = 7.0*hScale;//padding
    totalPadding += joinCaptionPadding;
    //captionLabel
    if (!_captionLabel) {
        self.captionLabel = [QMUILabel new];
        self.captionLabel.textColor = [UIColor qmui_colorWithHexString:@"#FF0300"];
        self.captionLabel.font = [UIFont systemFontOfSize:11.0 weight:UIFontWeightRegular];
        self.captionLabel.textAlignment = NSTextAlignmentCenter;
        self.captionLabel.numberOfLines = 0;
        [self.snapshotContentView addSubview:self.captionLabel];
        [self.captionLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(self.joinCaptionLabel.mas_bottom).offset(joinCaptionPadding);
            make.centerX.mas_equalTo(self.snapshotContentView);
            make.width.mas_equalTo(self.nameLabel);
        }];
    }
    self.captionLabel.text = self.shareData.text.text;
    CGFloat captionPadding = 14.0*hScale;//padding
    totalPadding += captionPadding;
    
    
    [self.contentScroll layoutIfNeeded];
    [self.contentView layoutIfNeeded];
    CGFloat headMidY = CGRectGetMidY(self.headImageView.frame);
    //设置topLayer的path
    CGFloat quadCurveHeight = 40.0*hScale;
    UIBezierPath *topLayerPath = [UIBezierPath bezierPath];
    [topLayerPath moveToPoint:CGPointZero];
    [topLayerPath addLineToPoint:CGPointMake(0, headMidY-quadCurveHeight/2)];
    [topLayerPath addQuadCurveToPoint:CGPointMake(width, headMidY-quadCurveHeight/2) controlPoint:CGPointMake(width/2, headMidY+quadCurveHeight/2)];
    [topLayerPath addLineToPoint:CGPointMake(width, 0)];
    [topLayerPath closePath];
    //
    self.topLayer.path = topLayerPath.CGPath;
    
    //计算高度
    CGFloat contentHeight = 0;
    contentHeight += totalPadding;
    contentHeight += CGRectGetHeight(self.titleLabel.frame);
    contentHeight += CGRectGetHeight(self.amountLabel.frame);
    contentHeight += CGRectGetHeight(self.headImageView.frame);
    contentHeight += CGRectGetHeight(self.nameLabel.frame);
    contentHeight += CGRectGetHeight(self.recommendLabel.frame);
    contentHeight += CGRectGetHeight(self.qrIV.frame);
    contentHeight += CGRectGetHeight(self.joinCaptionLabel.frame);
    contentHeight += CGRectGetHeight(self.captionLabel.frame);
    //
    self.contentHeight = contentHeight;
    self.contentScroll.contentSize = CGSizeMake(0, contentHeight);
    self.contentView.center = CGPointMake(ScreenWidth/2, ScreenHeight/2);
    //
    [self.snapshotContentView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(contentHeight);
    }];
    
    CGFloat viewButtonPadding = 20.0*hScale;//按钮和contentView的间距
    if (!_shareRewardButton) {
        self.shareRewardButton = [QMUIButton new];
        self.shareRewardButton.imagePosition = QMUIButtonImagePositionTop;
        self.shareRewardButton.spacingBetweenImageAndTitle = 7.0*hScale;
        [self.shareRewardButton setImage:LOAD_IMAGE(@"share_reward") forState:UIControlStateNormal];
        [self.shareRewardButton setTitleColor:[UIColor qmui_colorWithHexString:@"#FFFFFF"] forState:UIControlStateNormal];
        self.shareRewardButton.titleLabel.font = [UIFont systemFontOfSize:13 weight:UIFontWeightRegular];
        [self.view addSubview:self.shareRewardButton];
        [self.shareRewardButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(self.contentView.mas_bottom).offset(viewButtonPadding);
            make.centerX.mas_equalTo(self.contentView);
        }];
        //
        [self.shareRewardButton addTarget:self action:@selector(shareRewardButtonDidClickedAction) forControlEvents:UIControlEventTouchUpInside];
    }
    [self.shareRewardButton setTitle:self.shareData.text.butt_text forState:UIControlStateNormal];
    //
    [self.view layoutIfNeeded];
    CGSize shareButtonSize = self.shareRewardButton.frame.size;
    //计算布局了
    CGFloat viewTotleHeight = CGRectGetHeight(self.view.frame)-Height_StatusBar-Height_Bottom_SafeArea;
    CGFloat viewTopPadding = 10.0*hScale;//顶部间距
    CGFloat viewBottomPadding = 10.0*hScale;//底部间距
    
    //
    viewTotleHeight -= (viewTopPadding+viewBottomPadding+viewButtonPadding);
    //
    CGFloat realHeight = self.contentHeight+viewButtonPadding+shareButtonSize.height;
    //
    if (viewTotleHeight<=realHeight) {//不够缩减contentView的height
        CGFloat changeContentHeight = viewTotleHeight-viewButtonPadding-shareButtonSize.height;
        self.contentView.qmui_top = viewTopPadding+Height_StatusBar;
        self.contentView.qmui_height = changeContentHeight;
    }else {
        CGFloat offset = (viewTotleHeight-realHeight)/2+viewTopPadding;
        self.contentView.qmui_top = offset+Height_StatusBar;
        self.contentView.qmui_height = self.contentHeight;
    }
    [self.view layoutIfNeeded];
    [self showContentAnimation];
}
- (void)showContentAnimation {
    self.contentView.transform = CGAffineTransformMakeScale(0, 0);
    self.shareRewardButton.alpha = 0;
    [UIView animateWithDuration:1 delay:0 usingSpringWithDamping:1 initialSpringVelocity:1 options:UIViewAnimationOptionCurveLinear animations:^{
        self.contentView.transform = CGAffineTransformMakeScale(1, 1);
        self.shareRewardButton.alpha = 1;
    } completion:^(BOOL finished) {
    }];
}



#pragma mark - request
/**
 请求分享数据
 */
- (void)requestShareData {
    [self.view bc_showLoading];
    //
    BCUserShareRequest *request = [BCUserShareRequest new];
    //
    WEAK_SELF
    [request didRequestCompleted:^{
        [wself.view bc_hiddenLoading];
    }];
    [request didRequestSuccessed:^(id result, id page) {
        BCUserShareResponse *resp = result;
        [wself handleData:resp.data];
    }];
    [request didRequestFailed:^(NSError *error) {
        if (error&&wself.fromController) {
            NSString *errorMsg = error.domain;
            [QMUITips showError:errorMsg inView:wself.fromController.view hideAfterDelay:[QMUITips smartDelaySecondsForTipsText:errorMsg]];
            [wself dismissWindow];
        }
    }];
    [request requestServer];
}

//
- (void)handleData:(BCUserShareData *)respData {
    if (respData) {
        self.shareData = respData;
        [self loadContentView:[self contentWidth]];
    }
}



#pragma mark - shareRewardButtonDidClickedAction
/**
 点击了分享有奖按钮
 */
- (void)shareRewardButtonDidClickedAction {
    WEAK_SELF
    self.captionLabel.alpha = 0;//不需要下面这个提示
    UIImage *shareImage = [self.snapshotContentView qmui_snapshotLayerImage];
    self.captionLabel.alpha = 1;
    NSString *shareText = BCLocalizedKey(@"CFBundleDisplayName");
//    NSURL *shareUrl = [NSURL URLWithString:@""];
//    NSArray *items = @[shareText,shareImage,shareUrl];
    NSArray *items = @[shareText,shareImage];
    UIActivityViewController *activityVC = [[UIActivityViewController alloc] initWithActivityItems:items applicationActivities:nil];
    //
    NSArray *excludedActivityTypes = @[UIActivityTypeAirDrop,UIActivityTypeCopyToPasteboard,UIActivityTypeAddToReadingList,UIActivityTypeOpenInIBooks,UIActivityTypePostToFlickr,UIActivityTypePrint];
    NSMutableArray *newExcluded = [NSMutableArray arrayWithArray:excludedActivityTypes];
    if (@available(iOS 11.0,*)) {
        [newExcluded addObject:UIActivityTypeMarkupAsPDF];
    }
    //
    activityVC.excludedActivityTypes = newExcluded;
    UIActivityViewControllerCompletionWithItemsHandler itemsBlock = ^(UIActivityType __nullable activityType, BOOL completed, NSArray * __nullable returnedItems, NSError * __nullable activityError){
        if (completed == YES) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [wself dismissWindow];
            });
        }else{
           
        }
    };
    activityVC.completionWithItemsHandler = itemsBlock;
    [self presentViewController:activityVC animated:true completion:nil];
}





- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [super touchesBegan:touches withEvent:event];
    //
//    UITouch *touch = touches.anyObject;
//    CGPoint touchPoint = [touch locationInView:self.view];
    //
    [self dismissWindow];
}

@end
